package dubbo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.MethodConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.alibaba.dubbo.rpc.service.GenericService;

public class DubboRegistry {

	/**
	 * 注册一个提供者
	 * @param addr
	 * @param protocolName
	 * @param part
	 * @param appName
	 * @param interfaceName
	 * @param version
	 * @param filterName
	 */
	public static void registryInterface(String addr,String protocolName,int part,String appName,String interfaceName,String version,String filterName){
		// 连接注册中心配置
		RegistryConfig registry = new RegistryConfig();
		registry.setAddress(addr);
		ProtocolConfig protocolConfig = new ProtocolConfig();
		protocolConfig.setName(protocolName);
		protocolConfig.setPort(part);
		ApplicationConfig applicationConfig = new ApplicationConfig();
		applicationConfig.setName("provider");
		//		List<MethodConfig> methods = new ArrayList<MethodConfig>();
		//		MethodConfig methodConfig = new MethodConfig();
		//		methodConfig.setName("test");
		//		methods.add(methodConfig);
		// 服务提供者暴露服务配置
		ServiceConfig service = new ServiceConfig(); 	// 此实例很重，封装了与注册中心的连接，请自行缓存，否则可能造成内存和连接泄漏
		service.setApplication(applicationConfig);
		service.setRegistry(registry); 					// 多个注册中心可以用setRegistries()
		service.setProtocol(protocolConfig);	 		// 多个协议可以用setProtocols()
		//		service.setInterface(GenericService.class);
		service.setInterface(interfaceName);
		service.setRef(new CustomGenericService(interfaceName));
		if(filterName!=null){
			service.setFilter(filterName);
		}
		//		service.setMethods(methods);
		service.setVersion(version);
		service.export();
	}

	public static void main(String[] args) {
		{
			registryInterface("zookeeper://127.0.0.1:2181","dubbo",29000,"provider",
					"test.TestInterface","1.0.0","MyDubboFilterProvider"
					);
		}
		{
			registryInterface("zookeeper://127.0.0.1:2181","dubbo",29001,"provider",
					"test.TestInterface2","1.0.0",null
			);
		}
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
